<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2022/5/21
 * Time: 16:20
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\pay\controller;

use app\BaseController;
use app\common\model\MallOrder;
use EasyWeChat\Factory;
use Htlove\Str;
use think\App;
use think\facade\Cache;
use think\facade\Log;

class Notify extends BaseController
{
    protected $wechat_app = null;
    protected $mini_app = null;

    public function __construct(App $app)
    {
        $config = [
            'app_id' => sysconfig('weixin', 'wx_mini_app_id'),
            'mch_id' => sysconfig('weixin', 'wx_pay_mch_id'),
            'key' => sysconfig('weixin', 'wx_pay_key'),   // API 密钥

            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path' => public_path() . sysconfig('weixin', 'wx_pay_cert'), // XXX: 绝对路径！！！！
            'key_path' => public_path() . sysconfig('weixin', 'wx_pay_cert_key'),      // XXX: 绝对路径！！！！
        ];
        $this->wechat_app = Factory::payment($config);
        $this->mini_app = Factory::miniProgram([
            "app_id" => sysconfig('weixin', "wx_mini_app_id"),
            "secret" => sysconfig('weixin', 'wx_mini_secret_id'),
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => runtime_path('easywechat') . 'wechat.log',
            ],
        ]);
        parent::__construct($app);
    }

    public function index()
    {
        $response = $this->wechat_app->handlePaidNotify(function ($message, $fail) {
            Log::info("========================收到支付通知========================");
            Log::info($message);
            // 你的逻辑
            $obj = new MallOrder();
            $order = $obj->getOrderByOrderId($message['out_trade_no']);
            if (!$order) {
                return true;
            }
            $order_data = $order->toArray();
            if ($order_data['order_status'] != 0) {
                return true;
            }
            //查询订单
            $query_order = $this->wechat_app->order->queryByOutTradeNumber($order['order_sn']);
            Log::info("========================查询支付结果========================");
            Log::info($query_order);
            if ($query_order['return_code'] == "SUCCESS") {
                if ($query_order['result_code'] == "SUCCESS") {
                    if ($query_order['trade_state'] == "SUCCESS") {
                        //更新数据库
                        //查询是否有缓存
                        $key = "machine_order_data_machine" . date('Y-m-d').$order['machine_id'];
                        $number = Cache::get($key);
                        if (!$number) {
                            $number = 1;
                        }
                        $res = $obj->updateDataSave($order_data['id'], [
                            "order_status" => 1,
                            "pay_time" => strtotime(date('Y-m-d H:i:s', strtotime($query_order['time_end']))),
                            "update_time" => time(),
                            "order_number" => $number,
                        ]);
                        if ($res) {
                            //Cache::store('redis')->hset("machine_order_data", $order_data['machine_id'] . "~" . Str::getInstance()->create_trade_no(md5(date('Ymd'))), $order_data['order_sn']);
                            Cache::store('redis')->rpush("machine_order_data", $order_data['order_sn']);
                            Cache::set($key, $number++);
                            return true;
                        } else {
                            return $fail("更新订单失败");
                        }
                    } else {
                        return $fail("订单状态不正确！请稍后通知我");
                    }
                } else {
                    return $fail("业务状态不正确");
                }
            } else {
                return $fail("状态不正常");
            }
        });

        $response->send(); // Laravel 里请使用：return $response;
    }
}